package com.d3works.apps.base.rest.http;

import org.apache.commons.lang3.StringUtils;

public abstract class RestTemplate implements RequestEvent<String> {

  @Override
  public void onRequest(Object body, RequestEventArgs request) throws Exception {

    beforeRequest(request);
    if (HttpClient.GET.equals(request.getMethod())) {

    } else {
      request.jsonPost();
      request.writeRequestBody(body);
    }
  }

  /**
   * 发出请求前，用于设置权限信息
   *
   * @param request
   */
  protected abstract void beforeRequest(RequestEventArgs request) throws Exception;

  @Override
  public String onResponsed(ResponseEventArgs response) throws Exception {
    return response.getResponseText();
  }

  /**
   * get 请求
   *
   * @param url
   * @param params 转换为URL参数
   * @return
   * @throws Exception
   */
  public String get(String url, Object params) throws Exception {
    String strRequestParam = HttpClient.getRequestParam(params);
    if (StringUtils.isNotEmpty(strRequestParam)) {
      String lk = url.contains("?") ? "&" : "?";
      url = String.format("%s%s%s", url, lk, strRequestParam);
    }
    return HttpClient.get(url, this);
  }

  /**
   * @param url
   * @param data
   * @return
   * @throws Exception
   */
  public String post(String url, Object data) throws Exception {
    return HttpClient.post(url, data, this);
  }
}
